package com.wanghlme.day29.Controller;

import com.wanghlme.day29.util.ActionMapping;
import com.wanghlme.day29.util.ActionResult;
import com.wanghlme.day29.util.DomForJavaParse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

//@WebServlet(urlPatterns = {"*.do"})
public class FrontControllerBack extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(FrontControllerBack.class);
    private Map<String, ActionMapping> map;

    @Override
    public void init() throws ServletException {
        map = DomForJavaParse.parseXmlByDom();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        logger.debug("本次请求的 Uri 是：{}", uri);
        int begin = uri.indexOf("/", 1);
        int end = uri.lastIndexOf(".");
        String path = uri.substring(begin, end);
        ActionMapping actionMapping = map.get(path);
        if (actionMapping != null) {
            String className = actionMapping.getClassName();
            logger.debug("{}对应的后端控制器的完全限定名为{}", path, className);
            Class<?> cls;
            ICommand addAction = null;
            try {
                //通过反射，创建后端控制器实例，将请求交给其处理
                cls = Class.forName(className);
                addAction = (ICommand) cls.getDeclaredConstructor().newInstance();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
            assert addAction != null;
            String nextPage = addAction.execute(req, resp);
            logger.debug("后端控制器返回的逻辑名是{}", nextPage);
            Map<String, ActionResult> resultMap = actionMapping.getResultMap();
            ActionResult result = resultMap.get(nextPage);
            if (result != null) {
                String realPath = result.getPath();
                logger.debug("{}对应的页面信息是{}", nextPage, realPath);
                req.getRequestDispatcher(realPath).forward(req, resp);
            } else {
                logger.debug("没有找到{}对应的页面信息", nextPage);
            }
        } else {
            logger.debug("根据{}没有找到对应的映射！", path);
        }
    }
}
